package cn.gz.demo.ui.animation;


import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;

import androidx.databinding.DataBindingUtil;

import cn.gz.demo.R;
import cn.gz.demo.databinding.AnimationSetBinding;
import cn.gz.demo.ui.base.BaseActivity;

/**
 * Created by Liuyz on 2019/7/11.
 */

public class AnimationSetActivity extends BaseActivity {

    private AnimationSetBinding binding;
    private AnimationSet s1, s2;
    private TranslateAnimation t1, t2;
    private AlphaAnimation a1, a2;
    private String[] msg = {"1111", "22222", "33333", "44444", "5555"};
    private int index = 0;
    private AnimationDrawable animation;

    // 持有这个动画的引用，让他可以在动画执行中途取消
    private Animator mCurrentAnimator;
    private int mShortAnimationDuration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_animation_set);

        initView();
        initOtherView();
    }

    private void initOtherView() {
        binding.imageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zoomImageFromThumb(binding.imageView1, R.mipmap.ic_launcher);
            }
        });
        binding.imageView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zoomImageFromThumb(binding.imageView2, R.mipmap.ic_launcher);
            }
        });
        binding.imageView3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.imageView3.setBackgroundResource(R.drawable.chat_location_bg);
                animation = (AnimationDrawable)  binding.imageView3.getBackground();
                animation.start();
            }
        });

        // 系统默认的短动画执行时间 200
        mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
    }

    private void initView() {
        s1 = new AnimationSet(true);
        s1.setRepeatMode(Animation.RESTART);
        s1.setFillAfter(true);
        s1.setRepeatCount(1);

        t1 = new TranslateAnimation(0, 0, 0, -200);
        t1.setDuration(1500);
        a1 = new AlphaAnimation(0, 1);
        a1.setDuration(1500);

        s1.addAnimation(t1);
        s1.addAnimation(a1);


        s2 = new AnimationSet(true);
        s2.setRepeatMode(Animation.RESTART);
        s2.setFillAfter(false);
        s2.setRepeatCount(1);

        t2 = new TranslateAnimation(0, 0, -200, -400);
        t2.setDuration(1500);
        a2 = new AlphaAnimation(1, 0);
        a2.setDuration(1500);

        s2.addAnimation(t2);
        s2.addAnimation(a2);

        binding.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.iv.setText(msg[index]);
                ++index;
                binding.iv.setAnimation(s1);
                binding.iv.startAnimation(s1);
            }
        });

        s1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        binding.iv.setAnimation(s2);
                        binding.iv.startAnimation(s2);
                    }
                }, 1000);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        s2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                binding.iv.setVisibility(View.GONE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (index < msg.length) {
                            binding.iv.setVisibility(View.VISIBLE);
                            binding.iv.setText(msg[index]);
                            ++index;
                            binding.iv.setAnimation(s1);
                            binding.iv.startAnimation(s1);
                        }
                    }
                }, 500);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void zoomImageFromThumb(final View thumbView, int imageResId) {
        // 如果有动画正在运行，取消这个动画
        if (mCurrentAnimator != null) {
            mCurrentAnimator.cancel();
        }

        // 加载显示大图的ImageView
        binding.expandedImage.setImageResource(imageResId);

        // 计算初始小图的边界位置和最终大图的边界位置。
        final Rect startBounds = new Rect();
        final Rect finalBounds = new Rect();
        final Point globalOffset = new Point();

        // 小图的边界就是小ImageView的边界，大图的边界因为是铺满全屏的，所以就是整个布局的边界。
        // 然后根据偏移量得到正确的坐标。
        thumbView.getGlobalVisibleRect(startBounds);
        findViewById(R.id.container).getGlobalVisibleRect(finalBounds, globalOffset);
        startBounds.offset(-globalOffset.x, -globalOffset.y);
        finalBounds.offset(-globalOffset.x, -globalOffset.y);

        // 计算初始的缩放比例。最终的缩放比例为1。并调整缩放方向，使看着协调。
        float startScale = 0;
        if ((float) finalBounds.width() / finalBounds.height() > (float) startBounds.width() / startBounds.height()) {
            // 横向缩放
            float startWidth = startScale * finalBounds.width();
            float deltaWidth = (startWidth - startBounds.width()) / 2;
            startBounds.left -= deltaWidth;
            startBounds.right += deltaWidth;
        } else {
            // 竖向缩放
            float startHeight = startScale * finalBounds.height();
            float deltaHeight = (startHeight - startBounds.height()) / 2;
            startBounds.top -= deltaHeight;
            startBounds.bottom += deltaHeight;
        }

        // 隐藏小图，并显示大图
        thumbView.setAlpha(0f);
        binding.expandedImage.setVisibility(View.VISIBLE);

        // 将大图的缩放中心点移到左上角。默认是从中心缩放
        binding.expandedImage.setPivotX(0f);
        binding.expandedImage.setPivotY(0f);

        //对大图进行缩放动画
        AnimatorSet set = new AnimatorSet();
        set.play(ObjectAnimator.ofFloat(binding.expandedImage, View.X, startBounds.left, finalBounds.left))
                .with(ObjectAnimator.ofFloat(binding.expandedImage, View.Y, startBounds.top, finalBounds.top))
                .with(ObjectAnimator.ofFloat(binding.expandedImage, View.SCALE_X, startScale, 1f))
                .with(ObjectAnimator.ofFloat(binding.expandedImage, View.SCALE_Y, startScale, 1f));
        set.setDuration(mShortAnimationDuration);
        set.setInterpolator(new DecelerateInterpolator());
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mCurrentAnimator = null;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                mCurrentAnimator = null;
            }
        });
        set.start();
        mCurrentAnimator = set;

        // 点击大图时，反向缩放大图，然后隐藏大图，显示小图。
        final float startScaleFinal = startScale;
        binding.expandedImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCurrentAnimator != null) {
                    mCurrentAnimator.cancel();
                }

                AnimatorSet set = new AnimatorSet();
                set.play(ObjectAnimator
                        .ofFloat(binding.expandedImage, View.X, startBounds.left))
                        .with(ObjectAnimator.ofFloat(binding.expandedImage, View.Y, startBounds.top))
                        .with(ObjectAnimator.ofFloat(binding.expandedImage, View.SCALE_X, startScaleFinal))
                        .with(ObjectAnimator.ofFloat(binding.expandedImage, View.SCALE_Y, startScaleFinal));
                set.setDuration(mShortAnimationDuration);
                set.setInterpolator(new DecelerateInterpolator());
                set.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        thumbView.setAlpha(1f);
                        binding.expandedImage.setVisibility(View.GONE);
                        mCurrentAnimator = null;
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                        thumbView.setAlpha(1f);
                        binding.expandedImage.setVisibility(View.GONE);
                        mCurrentAnimator = null;
                    }
                });
                set.start();
                mCurrentAnimator = set;
            }
        });
    }
}
